package com.sheng.controller;


import com.sheng.entity.Books;
import com.sheng.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    //controller 调service层
    @Autowired
    @Qualifier("bookServiceImpl")
    private BookService bookService;

    //查询全部的书籍，并且返回到一个书籍展示页面
    @RequestMapping("allBook")
    public String list(Model model){
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list",list);
        return "allBook";
    }

//  **********************增加**************************

    //跳转到增加书籍页面
    @RequestMapping("toAddBook")
    public String toAddPager(){
        return "addBook";
    }

    //添加书籍的请求
    @RequestMapping("addBook")
    public String addBook(Books books){
        bookService.addBook(books);
        return "redirect:/book/allBook";//重定向到我们的@RequestMapping（“allBook”）请求；
    }

//  **********************修改**************************

    //跳转到修改页面
    @RequestMapping("toUpdateBook/{id}")
    public String toUpdatePaper(@PathVariable int id,Model model){
        Books books = bookService.queryBookById(id);
        model.addAttribute("books",books);
        return "updateBook";
    }

    //修改书籍请求
    @RequestMapping("updateBook")
    public String updateBook(Books books){
        bookService.updateBook(books);
        return "redirect:/book/allBook";
    }

//  **********************删除**************************
    //删除书籍请求
    @RequestMapping("deleteBook/{id}")
    public String deleteBook(@PathVariable int id){
        bookService.deleteById(id);
        return "redirect:/book/allBook";
    }

//  **********************查询一本书**************************
    @RequestMapping("/queryBook")
    public String queryBook(@RequestParam("queryBookName") String name, Model model){
        Books books = bookService.queryBookByName(name);
        List<Books> list = new ArrayList<Books>();
        list.add(books);
        if (books == null){
            model.addAttribute("error","未查询到书籍");
            list = bookService.queryAllBook();
        }
        model.addAttribute("list",list);
        return "allBook";
    }
}
